<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Api_V2_Card
{
    private static $type_id = 198;

    public static function card_list($data)
    {
        $page = $data['page']?$data['page']:1;
        $limit = $data['page_size']?$data['page_size']:10;
        $offset = ($page-1) * $limit;
        $list = DB::select('id','title','sellprice','price','litpic','sellpoint','effective_type','start_date','end_date','effective_days','attrid')
            ->from('card')
            ->where('ishidden','=',0)
            ->order_by(DB::expr("IFNULL(displayorder,9999) asc,modtime desc,addtime DESC"))
            ->offset($offset)
            ->limit($limit)
            ->execute()
            ->as_array();
        foreach ($list as &$v){
            $v['litpic'] = Model_Api_V2_System::uniapp_img($v['litpic'], 216, 216);
            if($v['effective_type']==1){
                $v['effective_name'] = '永久有效';
            }elseif ($v['effective_type']==2){
                $v['effective_name'] = date('Y-m-d',$v['start_date']).' 至 '.date('Y-m-d',$v['end_date']);
            }else{
                $v['effective_name'] = $v['effective_days'].'天';
            }
            if($v['attrid']){
                $attr_list = DB::select('id','attrname')->from("card_attr")->where("id IN({$v['attrid']}) and pid!=0")->execute()->as_array();
            }else{
                $attr_list = array();
            }
            $v['attr_list'] = $attr_list;
        }
        return $list;
    }

    public static function card_detail($data)
    {
        $field = "id,title,sellprice,price,number,effective_type,start_date,end_date,effective_days,sellpoint,attrid,type,people_number,is_real_name,use_number,refund_type,litpic,piclist,description,booking_information,product_description";
        $detail = DB::select(DB::expr($field))->from('card')->where("id={$data['card_id']}")->execute()->current();
        $detail['piclist'] = Model_Api_V2_System::get_product_piclist($detail['piclist']);
        $detail['litpic'] = Model_Api_V2_System::uniapp_img($detail['litpic'], 750, 400);
        if($detail['effective_type']==1){
            $detail['effective_name'] = '永久有效';
        }elseif($detail['effective_type']==2){
            $detail['effective_name'] = date('Y-m-d',$detail['start_date']).' 至 '.date('Y-m-d',$detail['end_date']);
        }else{
            $detail['effective_name'] = $detail['effective_days'].'天';
        }
        if($detail['attrid']){
            $attr_list = DB::select('id','attrname')->from("card_attr")->where("id IN({$detail['attrid']}) and pid!=0")->execute()->as_array();
        }else{
            $attr_list = array();
        }
        $detail['people_number'] = $detail['type']==0?1:$detail['people_number'];
        $detail['attr_list'] = $attr_list;
        $extended_content = DB::select('chinesename','columnname','issystem')
            ->from('card_content')
            ->where("isopen=1")
            ->order_by('displayorder','asc')
            ->execute()
            ->as_array();
        foreach ($extended_content as &$v){
            if($v['issystem']==1){
                $v['content'] = Model_Api_V2_Xcx::filter_content($detail[$v['columnname']]);
            }else{
                $content = DB::select()->from('card_extend_field')->where("productid={$data['card_id']}")->execute()->get($v['columnname']);
                $v['content'] = Model_Api_V2_Xcx::filter_content($content);
            }
        }
        unset($detail['booking_information']);
        unset($detail['product_description']);
        $detail['extended_content'] = $extended_content;

        return $detail;
    }

    public static function member_card_detail($data)
    {
        $field = "id,card_name as title,sellprice,price,effective_type,start_date,card_id,attrid,end_date,effective_days,sellpoint,type,people_number,is_real_name,use_number,refund_type,litpic,piclist,description,booking_information,product_description";
        $detail = DB::select(DB::expr($field))->from('card_member')->where("id={$data['member_card_id']}")->execute()->current();
        $detail['piclist'] = Model_Api_V2_System::get_product_piclist($detail['piclist']);
        $detail['litpic'] = Model_Api_V2_System::uniapp_img($detail['litpic'], 750, 400);
        if($detail['effective_type']==1){
            $detail['effective_name'] = '永久有效';
        }elseif($detail['effective_type']==2){
            $detail['effective_name'] = date('Y-m-d',$detail['start_date']).' 至 '.date('Y-m-d',$detail['end_date']);
        }else{
            $detail['effective_name'] = $detail['effective_days'].'天';
        }
        if($detail['attrid']){
            $attr_list = DB::select('id','attrname')->from("card_attr")->where("id IN({$detail['attrid']}) and pid!=0")->execute()->as_array();
        }else{
            $attr_list = array();
        }
        $detail['attr_list'] = $attr_list;
        $detail['people_number'] = $detail['type']==0?1:$detail['people_number'];
        $extended_content = DB::select('chinesename','columnname','issystem')
            ->from('card_content')
            ->where("isopen=1")
            ->order_by('displayorder','asc')
            ->execute()
            ->as_array();
        foreach ($extended_content as &$v){
            if($v['issystem']==1){
                $v['content'] = Model_Api_V2_Xcx::filter_content($detail[$v['columnname']]);
            }else{
                $content = DB::select()->from('card_extend_field')->where("productid={$detail['card_id']}")->execute()->get($v['columnname']);
                $v['content'] = Model_Api_V2_Xcx::filter_content($content);
            }
        }
        unset($detail['booking_information']);
        unset($detail['product_description']);
        $detail['extended_content'] = $extended_content;

        return $detail;
    }

    public static function card_book($data)
    {
        $card = DB::select()->from('card')->where("id={$data['card_id']}")->execute()->current();
        if(!$card){
            throw new Exception('会员卡已下架');
        }
        $tourer = DB::select()->from('member_linkman')->where("id IN({$data['tourer_id']})")->execute()->as_array();
        if(!$tourer){
            throw new Exception('旅客信息错误！');
        }
        foreach ($tourer as $v) {
            if(empty($v['mobile'])){
                throw new Exception('旅客手机号不得为空');
            }
        }
        if($card['for_purchas']>0){
            $num = DB::select()->from('member_order')
                ->where("typeid",'=',"198")
                ->and_where('memberid','=',$data['member_id'])
                ->and_where('productautoid','=',$card['id'])
                ->and_where('status','IN',array(0,1,2,5,6))
                ->execute()->count();
            if($num>=$card['for_purchas']){
                throw new Exception('预订次数超限');
            }
        }
        $litpic = explode('||',$card['litpic']);
        $order = array(
            'memberid'            => $data['member_id'],
            'webid'               => 0,
            'typeid'              => self::$type_id,
            'ordersn'             => St_Product::get_ordersn(self::$type_id),
            'productname'         => $card['title'],
            'productautoid'       => $card['id'],
            'suitid'              => $card['id'],
            'litpic'              => $litpic[0],
            'price'               => $card['price'],
            'dingnum'             => 1,
            'addtime'             => time(),
            'refund_restriction'  => $card['refund_type']==1?0:1,
        );

        $out = Model_Api_V2_Order::add_order($order, 'Model_Card');
        if($out['status']){
            $order = DB::select()->from('member_order')->where("ordersn='{$order['ordersn']}'")->execute()->current();
            self::save_card_purchase_record($tourer,$order,$card);
            self::save_member_product_record($card,$order);
            return array(
                'status' => true,
                'msg'    => '下单成功',
                'data'   => $order
            );
        }else{
            return array(
                'status' => false,
                'msg'    => $out['msg']
            );
        }
    }

    public static function save_member_product_record($card,$order)
    {
        $member_card_id = DB::select()->from('card_member')->where("order_id={$order['id']}")->execute()->get('id');
        $product = DB::select(DB::expr("id,{$member_card_id} as member_card_id,type_id,product_id,dest_id,attr_id,litpic,product_name"))
            ->from('card_product')
            ->where("card_id={$card['id']}")
            ->execute()
            ->as_array();
        foreach ($product as $v){
            $product_id = $v['id'];
            unset($v['id']);
            $id = DB::insert('card_member_product', array_keys($v))->values(array_values($v))->execute();
            if($id){
                $suit = DB::select(DB::expr("{$id[0]} as card_member_product_id,suit_id,suit_name,price,number"))
                    ->from('card_product_suit')
                    ->where("card_product_id={$product_id}")
                    ->execute()->as_array();
                foreach ($suit as $s){
                    DB::insert('card_member_product_suit', array_keys($s))->values(array_values($s))->execute();
                }
            }
        }
    }

    public static function save_card_purchase_record($tourer,$order,$card)
    {
        $card_member = array(
            'order_id'            => $order['id'],
            'card_id'             => $order['productautoid'],
            'card_num'            => '198'.date('mdH').rand(10000,99999),
            'card_name'           => $order['productname'],
            'member_id'           => $order['memberid'],
            'name'                => $tourer[0]['linkman'],
            'mobile'              => $tourer[0]['mobile'],
            'buy_time'            => time(),
            'price'               => $order['price'],
            'effective_type'      => $card['effective_type'],
            'start_date'          => $card['start_date'],
            'end_date'            => $card['end_date'],
            'effective_days'      => $card['effective_days'],
            'sellpoint'           => $card['sellpoint'],
            'type'                => $card['type'],
            'people_number'       => $card['people_number'],
            'is_real_name'        => $card['is_real_name'],
            'use_number'          => $card['use_number'],
            'refund_type'         => $card['refund_type'],
            'litpic'              => $card['litpic'],
            'attrid'              => $card['attrid'],
            'piclist'             => $card['piclist'],
            'description'         => $card['description'],
            'booking_information' => $card['booking_information'],
            'product_description' => $card['product_description'],
            'status'              => 1,
        );
        $is_exist = DB::select()->from('card_member')->where("order_id={$order['id']}")->execute()->valid();
        $c_m_id = false;
        if(!$is_exist){
            $c_m_id = DB::insert('card_member', array_keys($card_member))->values(array_values($card_member))->execute();
        }
        if(!$c_m_id){
            return false;
        }
        foreach ($tourer as $v){
            $id_card = DB::select()->from('card_member_associat')->where("id_card_no='{$v['idcard']}'")->execute()->current();
            if($id_card){
                $status = $id_card['status'];
            }else{
                $status = 0;
            }
            $card_member_associat = array(
                'c_m_id'     => $c_m_id[0],
                'name'       => $v['linkman'],
                'mobile'     => $v['mobile'],
                'id_card_no' => $v['idcard'],
                'status'     => $status,
                'addtime'    => time(),
            );
            $is_exist = DB::select()->from('card_member_associat')->where("c_m_id={$c_m_id[0]} and id_card_no='{$v['idcard']}'")->execute()->valid();

            if(!$is_exist){
                DB::insert('card_member_associat', array_keys($card_member_associat))->values(array_values($card_member_associat))->execute();
            }
        }
        return true;
    }

    public static function member_card_list($data)
    {
        $sql = "SELECT a.* FROM sline_card_member AS a ";
        $sql.= "LEFT JOIN sline_member_order AS b ON a.order_id=b.id ";
        $sql.= "WHERE b.status IN(2,5) and a.member_id={$data['member_id']} ";
        $sql.= "ORDER BY a.buy_time DESC ";
        $list = DB::query(1,$sql)->execute()->as_array();
        $card_list = array();
        foreach ($list as $v){
            if($v['attrid']){
                $attr_list = DB::select('id','attrname')->from("card_attr")->where("id IN({$v['attrid']}) and pid!=0")->execute()->as_array();
            }else{
                $attr_list = array();
            }
            $arr = array(
                'id'            => $v['id'],
                'card_num'      => $v['card_num'],
                'card_name'     => $v['card_name'],
                'litpic'        => Model_Api_V2_System::uniapp_img($v['litpic'], 442, 300),
                'piclist'       => Model_Api_V2_System::get_product_piclist($v['piclist']),
                'is_real_name'  => $v['is_real_name'],
                'attr_list'     => $attr_list,
                'real_name_num' => DB::select()->from('card_member_associat')->where("c_m_id={$v['id']} and status=1")->execute()->count(),
            );
            $arr['product_id'] = DB::select()->from('member_order')->where("id={$v['order_id']}")->execute()->get('productautoid');
            $arr['effective_name'] = Model_Card::get_effective_type($v);
            $arr['card_member'] = self::card_people_list(array('member_card_id'=>$v['id']));
            array_push($card_list,$arr);
        }

        return $card_list;
    }

    /**
     * @param $data
     * @return array
     * 获取会员卡产品列表
     */
    public static function card_product_list($data)
    {
        $page = $data['page']?:1;
        $page_size = $data['page_size']?:10;
        $page = ($page-1)*$page_size;
        $query = DB::select()->from('card_product')->where('card_id','=',$data['card_id']);
        if($data['keyword']){
            $query->and_where(DB::expr(" AND product_name like '%{$data['keyword']}%' "));
        }
        if($data['dest_id']){
            $query->and_where(DB::expr(" AND FIND_IN_SET({$data['dest_id']},dest_id) "));
        }
        $product = $query->order_by('id','asc')->offset($page)->limit($page_size)->execute()->as_array();
        foreach ($product as &$v){
            $pinyin = DB::select()->from('model')->where("id={$v['type_id']}")->execute()->get('pinyin');
            if($v['attr_id']){
                if($v['type_id']<200){
                    $v['attr'] = DB::select('attrname')->from($pinyin.'_attr')->where("id IN({$v['attr_id']}) and pid!=0")->execute()->as_array();
                }else{
                    $v['attr'] = DB::select('attrname')->from('model_attr')->where("id IN({$v['attr_id']}) and pid!=0")->execute()->as_array();
                }
            }else{
                $v['attr'] = array();
            }
            if($v['dest_id']){
                $dest = DB::select('kindname')->from('destinations')->where("id IN({$v['dest_id']}) and pid!=0")->execute()->as_array();
                $v['dest_name'] = implode(',',array_column($dest,'kindname'));
            }else{
                $v['dest_name'] = '';
            }
            $v['suit'] = DB::select()->from('card_product_suit')->where("card_product_id={$v['id']}")->execute()->as_array();
            $v['litpic'] = Model_Api_V2_System::uniapp_img($v['litpic'], 442, 300);
        }

        return array(
            'list' => $product,
        );
    }

    /**
     * @param $data
     * @return array
     * 获取已购卡产品列表
     */
    public static function member_card_product_list($data)
    {
        $page = $data['page']?:1;
        $page_size = $data['page_size']?:10;
        $page = ($page-1)*$page_size;
        $card_member = DB::select()->from('card_member')->where("id={$data['member_card_id']}")->execute()->current();
        $query = DB::select()->from('card_member_product')
            ->where("member_card_id",'=',$data['member_card_id']);
        if($data['keyword']){
            $query->and_where(DB::expr(" AND product_name like '%{$data['keyword']}%' "));
        }
        if($data['dest_id']){
            $query->and_where(DB::expr(" AND FIND_IN_SET({$data['dest_id']},dest_id) "));
        }
        $product = $query->order_by('id','asc')->offset($page)->limit($page_size)->execute()->as_array();
        $date = strtotime(date('Y-m-d'));
        foreach ($product as &$v) {
            $pinyin = DB::select()->from('model')->where("id={$v['type_id']}")->execute()->get('pinyin');
            $v['litpic'] = Model_Api_V2_System::uniapp_img($v['litpic'], 216, 216);
            if($v['dest_id']){
                $dest = DB::select('kindname')->from('destinations')->where("id IN({$v['dest_id']}) and pid!=0")->execute()->as_array();
                $v['dest_name'] = implode(',',array_column($dest,'kindname'));
            }else{
                $v['dest_name'] = '';
            }
            if($v['attr_id']){
                if($v['type_id']<200){
                    $v['attr'] = DB::select('attrname')->from($pinyin.'_attr')->where("id IN({$v['attr_id']}) and pid!=0")->execute()->as_array();
                }else{
                    $v['attr'] = DB::select('attrname')->from('model_attr')->where("id IN({$v['attr_id']}) and pid!=0")->execute()->as_array();
                }
            }else{
                $v['attr'] = array();
            }

            $v['suit'] = DB::select()->from('card_member_product_suit')->where("card_member_product_id={$v['id']}")->execute()->as_array();

            /*检测卡关联的产品是否还在售*/
            if($v['type_id']<200){
                $is_exist = DB::select()->from($pinyin)->where("id={$v['product_id']}")->execute()->current();
            }else{
                $pinyin = 'tongyong';
                $is_exist = DB::select()->from('model_archive')->where("id={$v['product_id']}")->execute()->current();
            }

            /*检测是否有每日限购次数 有的话库存就按限购来*/
            $v['number'] = self::get_number($card_member, $v, $pinyin);

            if($is_exist){
                $suit_id = DB::select()->from('card_member_product_suit')->where("card_member_product_id={$v['id']}")->execute()->as_array();
                $suit_id = implode(',',array_column($suit_id,'suit_id'));
                $model = $v['type_id']<200?'Model_'.strtoupper($pinyin):'Model_Card';
                $suit_list = $model::suit_list($v['product_id'],array('suit_id'=>$suit_id));
                if(count($suit_list)>0 && $suit_id){
                    $v['suit_id'] = $suit_id;
                    $v['status'] = true;
                    $v['status_name'] = '可预约';
                    /*酒店和租车返回一个默认时间*/
                    if($v['type_id']==2){
                        $day = DB::select(DB::expr("min(day) as day"))
                            ->from('hotel_room_price')
                            ->where("suitid IN({$suit_id}) and day>={$date}")
                            ->execute()
                            ->get('day');
                        $v['start_date'] = date('Y-m-d',$day);
                        $v['end_date'] = date('Y-m-d',$day+86400);
                    }elseif($v['type_id']==3){
                        $day = DB::select(DB::expr("min(day) as day"))
                            ->from('car_suit_price')
                            ->where("suitid IN({$suit_id}) and day>={$date}")
                            ->execute()
                            ->get('day');
                        $v['start_date'] = date('Y-m-d',$day);
                        $v['end_date'] = date('Y-m-d',$day);
                    }
                }else{
                    $v['suit_id'] = '';
                    $v['status'] = false;
                    $v['status_name'] = '已停售';
                }
            }else{
                $v['status'] = false;
                $v['status_name'] = '已下架';
            }
        }

        return array(
            'list'      => $product,
            'card_num'  => $card_member['card_num'],
            'card_name' => $card_member['card_name'],
            'is_real_name' => $card_member['is_real_name'],
        );
    }

    /**
     * @param $card_member
     * @param $data
     * @return mixed
     * 检测是否有每日限购次数 有的话库存就按限购来
     */
    public static function get_number($card_member, $data, $pinyin, $params=[])
    {
        $model = DB::select(DB::expr("max(number) as number"))
            ->from('card_member_product_suit')
            ->where("card_member_product_id","=",$data['id']);
        if($params['suit_id']){
            $model->where("suit_id","=",$params['suit_id']);
        }
        $suit_number = $model->execute()->get('number');
        if($suit_number>$card_member['use_number'] && $card_member['use_number']>0){
            $number = $card_member['use_number'];
        }else{
            $number = $suit_number;
        }

        if($params['type_id']){
            if($pinyin!='tongyong'){
                $table = St_Functions::table_field($params['type_id']);
                if(in_array($params['type_id'],[21,118,121])){
                    $pro_number = DB::select()->from($table[0])
                        ->where($table[1],"=",$data['product_id'])
                        ->and_where('id','=',$params['suit_id'])
                        ->execute()->get('number');
                }else{
                    $pro_number = DB::select()->from($table[6])
                        ->where($table[1],"=",$data['product_id'])
                        ->and_where($table[5],'=',$params['suit_id'])
                        ->and_where('day','=',strtotime($params['start_date']))
                        ->execute()->get('number');
                }
            }else{
                $pro_number = DB::select()->from('model_suit_price')
                    ->where("productid={$data['product_id']}")
                    ->and_where('suitid','=',$params['suit_id'])
                    ->and_where('day','=',strtotime($params['start_date']))
                    ->execute()->get('number');
            }
            if($pro_number!=-1){
                $number = min($pro_number, $number);
            }
        }

        return $number;
    }

    public static function member_card_product_detail($params)
    {
        $card_member = DB::select()->from('card_member')->where("id={$params['member_card_id']}")->execute()->current();
        $detail = DB::select()->from('card_member_product')
            ->where("member_card_id",'=',$params['member_card_id'])
            ->and_where("product_id",'=',$params['product_id'])
            ->and_where("type_id",'=',$params['type_id'])
            ->execute()->current();
        if($params['type_id']<200){
            $pinyin = DB::select()->from('model')->where("id={$params['type_id']}")->execute()->get('pinyin');
        }else{
            $pinyin = 'tongyong';
        }
        return self::get_number($card_member, $detail, $pinyin, $params);
    }

    public static function card_people_list($data)
    {
        $list = DB::select('id','name','mobile','id_card_no','status')
            ->from('card_member_associat')
            ->where("c_m_id={$data['member_card_id']} and is_del=0")
            ->execute()->as_array();
        foreach ($list as &$v){
            if($v['status']==0){
                $audit = DB::select()->from('card_realname_audit')->where("c_m_a_id={$v['id']}")->execute()->as_array();
                //查询是否已发起过实名审核
                if($audit){
                    $status = array_column($audit,'status');
                    if(in_array(0,$status)){
                        $v['status'] = 3;//待审核
                    }else{
                        $v['status'] = 2;//审核失败
                    }
                }
            }
        }
        return $list;
    }

    public static function card_realname_audit($data)
    {
        $member = DB::select()->from('card_member_associat')->where("id={$data['id']}")->execute()->current();
        if(!$member){
            throw new Exception('数据不存在');
        }
        $record = array(
            'c_m_a_id'         => $member['id'],
            'name'             => $data['name'],
            'id_card_no'       => $data['id_card_no'],
            'id_card_front'    => $data['id_card_front'],
            'id_card_opposite' => $data['id_card_opposite'],
            'addtime'          => time(),
        );
        $is_exist = DB::select()->from('card_realname_audit')
            ->where("c_m_a_id={$member['id']} and id_card_no='{$data['id_card_no']}' and status!=2")
            ->execute()->current();
        if($is_exist){
            throw new Exception('不可重复提交！');
        }else{
            $is_exist = DB::select()->from('card_realname_audit')
                ->where("id_card_no='{$data['id_card_no']}' and status!=2")
                ->execute()->current();
            if($is_exist){
                throw new Exception('身份证号已被使用！');
            }
            DB::insert('card_realname_audit', array_keys($record))->values(array_values($record))->execute();
        }
    }

    public static function order_detail($data)
    {
        $card_member = DB::select()->from('card_member')->where("order_id={$data['id']}")->execute()->current();
        $people_list = self::card_people_list(array('member_card_id'=>$card_member['id']));

        return $people_list;
    }

    public static function card_reservation_record($data)
    {
        $page = $data['page']?:1;
        $page_size = $data['page_size']?:10;
        $page = ($page-1)*$page_size;
        $type = $data['type']?:1;
        $member_card = DB::select()->from('card_member')->where("id={$data['member_card_id']}")->execute()->current();
        if(!$member_card){
            throw new Exception('卡信息不存在');
        }
        $sql = "SELECT a.id,a.ordersn,a.productname,a.productautoid,a.litpic,a.suit_name,a.status,a.usedate,a.departdate FROM sline_member_order AS a ";
        $sql.= "LEFT JOIN sline_card_member_reservation_record AS b ON(a.ordersn=b.order_sn) ";
        $sql.= "WHERE b.member_card_id={$data['member_card_id']} ";
        $sql.= $type==1?"AND a.status<5 ":"AND a.status=5 ";
        $total = DB::query(1, $sql)->execute()->count();
        $sql.= "ORDER BY b.addtime DESC ";
        $sql.= "LIMIT {$page},{$page_size} ";
        $list = DB::query(1, $sql)->execute()->as_array();
        foreach ($list as &$v){
            $v['litpic'] = Model_Api_V2_System::uniapp_img($v['litpic'], 180, 180);
            if($v['departdate']){
                $v['usedate'] = $v['usedate'].' 至 '.$v['departdate'];
            }

            switch ($v['status'])
            {
                case 0:
                case 6:
                    $v['status_name'] = '预约待审';
                    break;
                case 1:
                case 2:
                    $v['status_name'] = '预约成功';
                    break;
                case 3:
                case 4:
                    $v['status_name'] = '预约失败';
                    break;
                case 5:
                    $v['status_name'] = '行程结束';
                    break;
            }
        }

        return array(
            'list'  => $list,
            'total' => ceil(bcdiv($total, $page_size, 2)),
        );
    }
}